package com.wg.controller;

import com.wg.entity.User;
import com.wg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private UserService userService;
/**
 * 登录功能
 * */
    @RequestMapping("/loginIn")
    @ResponseBody
    public Map loginIn(@RequestBody User user, HttpServletRequest request){
        Map map=new HashMap();
        HttpSession session=request.getSession();
        User user1=userService.queryUserByNameAndPwd(user);
        System.out.println("login SESSION:" + session.getId());
        if(user1==null){
            map.put("code",404);
            map.put("msg","用户名或者密码错误");
            return map;
        }else{
            session.setAttribute("user",user1);
            map.put("code",200);
            map.put("user",user1);
            map.put("username",user1.name);
            return map;
        }

    }


    /**
     * 退出功能
     */
    @RequestMapping("/loginOut")
    public void loginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session=request.getSession();
        session.invalidate();
        response.sendRedirect(request.getContextPath()+"/login.html");
    }
}
